package com.cn.lf.wx;


import javax.sql.DataSource;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

@Configuration
public class DbConfig {
	
	@Autowired
    private Environment env;
	
	@Bean(name = "transactionManager")
	public PlatformTransactionManager prodTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
	    return new DataSourceTransactionManager(dataSource);
	}
    
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource")DataSource dataSource) throws Exception{
        MybatisSqlSessionFactoryBean fb = new MybatisSqlSessionFactoryBean();
        
        /*设置打印sql
         */
 		MybatisConfiguration configuration = new MybatisConfiguration();
 		//重点是这里,新建一个Configuration对象设置进去SqlSessionFactoryBean 
 		configuration.setLogImpl(StdOutImpl.class);
 		fb.setConfiguration(configuration);
 		
        fb.setDataSource(dataSource);
        fb.setTypeAliasesPackage(env.getProperty("mybatis-plus.type-aliases-package"));
        fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis-plus.mapper-locations")));
        
//        sqlsession 加上分页插件
        fb.setPlugins(new Interceptor[]{mybatisPlusInterceptor()});
        return fb.getObject();
    }
//    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
